package com.jims.api.v1.controller.common;

import com.alibaba.fastjson.JSONObject;
import com.jims.api.v1.controller.weixin.MyConfig;
import com.jims.api.v1.controller.weixin.WXPay;
import com.jims.api.v1.controller.weixin.WXPayUtil;
import com.jims.master.common.data.Message;
import com.jims.master.common.utils.SecurityUtil;
import com.jims.master.common.utils.SendSms;
import com.jims.master.common.utils.StringUtils;
import com.jims.master.modules.base.order.entity.Sorders;
import com.jims.master.modules.base.order.service.SordersService;
import com.jims.master.modules.base.user.entity.MasterBaseinfo;
import com.jims.master.modules.base.user.service.MasterBaseinfoService;
import com.jims.master.modules.patient.myRecord.entity.CaseReport;
import com.jims.master.modules.sys.entity.User;
import com.jims.master.modules.sys.service.UserService;
import com.jims.master.modules.sys.utils.DictUtils;
import com.jims.master.modules.weChatSweepPay.pay.HttpUtil;
import com.jims.master.modules.weChatSweepPay.pay.XMLUtil4jdom;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/12/27.
 */
@RestController
@RequestMapping(value = "WeiXinPay")
public class WeiXinPay {

    @Autowired
    private SordersService sordersService;
    @Autowired
    private UserService userService;
    @Autowired
    private MasterBaseinfoService masterBaseinfoService;

    /**
     * 微信统一下单接口
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "V100/WeiXinPay", method = {RequestMethod.GET, RequestMethod.POST})
    public String WeiXinPay(String orderId,String oppenId) throws Exception {
        MyConfig config = new MyConfig();
        Message msa = new Message();
        Sorders sorders =sordersService.get(orderId);
        Date start = sorders.getCreateDate();
        Date now = new Date();
        long between=(now.getTime()-start.getTime())/1000;
        int result = Integer.valueOf(String.valueOf(between/60));
        if(result<30){
            WXPay wxpay = new WXPay(config);
            Map<String, String> data = new HashMap<String, String>();
            data.put("body", sorders.getTitle());
            data.put("out_trade_no", sorders.getOrderNo());
            data.put("device_info", "WEB");
            data.put("fee_type", "CNY");
            Double d = sorders.getCost()*100;
            BigDecimal a=new BigDecimal(d);
            int b=a.intValue();
            data.put("total_fee", String.valueOf(b));
            //data.put("total_fee", "1");
            data.put("spbill_create_ip", "");//request.getRemoteAddr()
            data.put("notify_url", "http://www.jims-health.com:7150/WeiXinPay/V100/notify");
            data.put("trade_type", "JSAPI");
            data.put("sign_type", "MD5");
            data.put("product_id", "12");
            data.put("appid", config.getAppID());
            data.put("openid", oppenId);
            data.put("mch_id", config.getMchID());
            //获取统一下单的sign
            String sign = WXPayUtil.generateSignature(data, config.getKey());
            data.put("sign", sign);
            try {
                //微信统一下单接口，获取prepare_id
                Map<String, String> resp = wxpay.unifiedOrder(data);
                Date date = new Date();
                long times = date.getTime()/1000;
                //根据获取的prepare_id获取新的sign返回前台唤醒微信支付
                Map<String, String> map = new HashMap<>();
                map.put("appId",resp.get("appid"));
                map.put("nonceStr",resp.get("nonce_str"));
                map.put("package","prepay_id="+resp.get("prepay_id"));
                map.put("signType","MD5");
                map.put("timeStamp",String.valueOf(times));
                //获取到新的sign返回给前台
                String sign2 = WXPayUtil.generateSignature(map, config.getKey());
                map.put("sign",sign2);
                map.put("package",resp.get("prepay_id"));
                msa.setData(map);
                return SecurityUtil.encryptMsgData(msa);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }else {
            sorders.setDelFlag("1");
            sordersService.save(sorders);
            msa.setStatus("0");
            msa.setData(null);
            return SecurityUtil.encryptMsgData(msa);
        }

    }

   /**
     * @Description: （微信支付回调）
     * @author jict
     * @date 2017/12/28
     */
    @RequestMapping(value = "V100/notify", method = {RequestMethod.GET, RequestMethod.POST})
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 读取参数
        InputStream inputStream;
        MyConfig myConfig = new MyConfig();
        StringBuffer sb = new StringBuffer();
        inputStream = request.getInputStream();
        String s;
        BufferedReader in = new BufferedReader(new InputStreamReader(
                inputStream, "UTF-8"));
        while ((s = in.readLine()) != null) {
            sb.append(s);
        }
        in.close();
        inputStream.close();

        // 解析xml成map
        Map<String, String> m = new HashMap<String, String>();
        m = XMLUtil4jdom.doXMLParse(sb.toString());

        // 过滤空 设置 TreeMap
        SortedMap<Object, Object> packageParams = new TreeMap<Object, Object>();
        Iterator it = m.keySet().iterator();
        while (it.hasNext()) {
            String parameter = (String) it.next();
            String parameterValue = m.get(parameter);
            String v = "";
            if (null != parameterValue) {
                v = parameterValue.trim();
            }
            packageParams.put(parameter, v);
        }

        // 账号信息
        String key = myConfig.getKey(); // key

        // 判断签名是否正确
        if (WXPayUtil.isTenpaySign("UTF-8", packageParams, key)) {
            // ------------------------------
            // 处理业务开始
            // ------------------------------
            String resXml = "";
            if ("SUCCESS".equals((String) packageParams.get("result_code"))) {
                // 这里是支付成功
                // ////////执行自己的业务逻辑////////////////
                String mch_id = (String) packageParams.get("mch_id");
                String openid = (String) packageParams.get("openid");
                String is_subscribe = (String) packageParams.get("is_subscribe");
                String out_trade_no = (String) packageParams.get("out_trade_no");
                String total_fee = (String) packageParams.get("total_fee");
                //微信交易号
                String transaction_id = (String) packageParams.get("transaction_id");
                Sorders sorders =sordersService.getSordersByOrderNo(out_trade_no);
                //设置支付成功
                sorders.setOrderState("1");
                //设置微信交易号
                sorders.setAlipyNo(transaction_id);
                sorders.setPaymentTime(new Date());
                //付款方式为微信支付
                sorders.setAlipyStyle("0");
                int result = sordersService.save(sorders);
               /*//支付成功发送短信提醒
                User patientUser = userService.get(sorders.getPersonId());
                MasterBaseinfo patientBaseInfo = masterBaseinfoService.get(patientUser.getPersionId());
                User doctorUser = userService.get(sorders.getDoctorId());
                MasterBaseinfo doctorBaseInfo = masterBaseinfoService.get(doctorUser.getPersionId());
                if(StringUtils.isNoneBlank(patientBaseInfo.getMasterContactinfo().getMobilePhone()))
                    //客户提醒
                    SendSms.sendSmsO(patientBaseInfo.getMasterContactinfo().getMobilePhone(), "尊敬的" + patientBaseInfo.getName() + "您购买的" + sorders.getTitle() + " 服务，服务时间为：" + sorders.getStartTime().toString().substring(0, 10) + DictUtils.getDictLabel(sorders.getTimeType(), "timetype", "") + "，欢迎您使用康需平台。");
                if(StringUtils.isNoneBlank(doctorBaseInfo.getMasterContactinfo().getMobilePhone()))
                    //医生提醒
                    SendSms.sendSmsO(doctorBaseInfo.getMasterContactinfo().getMobilePhone(), "尊敬的" + doctorBaseInfo.getName() + "，"+patientBaseInfo.getName()+"购买了您的"+sorders.getTitle()+" 服务，服务时间为："+sorders.getStartTime().toString().substring(0,10)+ DictUtils.getDictLabel(sorders.getTimeType(), "timetype", "")+"，欢迎您使用康需平台。");*/
                if(result>0){
                    //*request.getSession().setAttribute("_PAY_RESULT", "OK");
                    HttpUtil._PAY_RESULT ="ok";
                    System.out.println("支付成功");
                    // 通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
                    resXml = "<xml>"
                            + "<return_code><![CDATA[SUCCESS]]></return_code>"
                            + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
                }

            } else {
                resXml = "<xml>"
                        + "<return_code><![CDATA[FAIL]]></return_code>"
                        + "<return_msg><![CDATA[报文为空]]></return_msg>"
                        + "</xml> ";
            }
            // ------------------------------
            // 处理业务完毕
            // ------------------------------
            BufferedOutputStream out = new BufferedOutputStream(
                    response.getOutputStream());
            out.write(resXml.getBytes());
            out.flush();
            out.close();
            } else {
                System.out.println("通知签名验证失败");
            }

        }

}